//
//  RadioDetailTableViewController.m
//  SuiRan
//
//  Created by lanou3g on 15-4-28.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import <objc/runtime.h>


#import "RadioDetailTableViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "Radio.h"
#import "RadioDetail.h"
#import "RadioInfo.h"
#import "RadioDetailTableViewCell.h"
#import "RadioDetailContactViewController.h"
#import "MJRefresh.h"
#import "playInfo.h"
#import "AudioPlayer.h"
#import "AudioStreamer.h"
#import "RadioDetailListTableViewController.h"



@interface RadioDetailTableViewController ()
@property (nonatomic, retain) NSMutableArray *radioListArray;
@property (nonatomic, retain) NSMutableArray *unameSenderArray;

@property (nonatomic, retain) NSString *coverimg;
@property (nonatomic, retain) NSString *uname;
@property (nonatomic, retain) NSMutableArray *unameArray;
@property (nonatomic, retain) NSString *icon;
@property (nonatomic, retain) NSString *musicvisitnum;
@property (nonatomic, retain) NSString *desc;
@property (nonatomic, assign) NSInteger startNumber;
@property (nonatomic, retain) NSMutableArray *tingidArray;
@property (nonatomic, retain) RadioDetailContactViewController * rdCVC;

@property (nonatomic, retain) NSMutableArray *titleArray;

// 计数数组
@property (nonatomic, retain) NSMutableArray *countArray;




@end

@implementation RadioDetailTableViewController





static NSString * const reuseIdentifier = @"RadioDetailTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationItem.title = _radio.title;
    
    // 注册tableView
    [self.tableView registerNib:[UINib nibWithNibName:@"RadioDetailTableViewCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    
    //设置返回播放页面的按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"radio"] style:UIBarButtonItemStylePlain target:self action:@selector(returnButtonAction:)];
    
    
    
    [self JSONData];
    [self refreshData];
    
    
}
#pragma mark - 设置返回播放页面
- (void)returnButtonAction:(UIButton *)button
{
    if (self.rdCVC == nil) {

        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"请任选一个节目" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
        [alertView show];
        
    }else
    {
        [self.navigationController pushViewController:self.rdCVC animated:YES];
    }
}

#pragma mark - 上拉、下拉
- (void)refreshData
{
    
    __block typeof(self)weakSelf = self;
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        
        [self JSONData];
        NSLog(@"下拉刷新");
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView reloadData];
        _startNumber = 0;
        
    }];
    
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [self refreshJSonData];
        [self.tableView.footer setTitle:@"" forState:MJRefreshFooterStateIdle];
        
        NSLog(@"上拉加载");
        [weakSelf.tableView.footer endRefreshing];
        [weakSelf.tableView reloadData];
        
    }];
    [self.tableView.footer setTitle:@"" forState:MJRefreshFooterStateIdle];

}



#pragma mark - JSON解析数据

- (void)JSONData
{
    self.radioListArray = [NSMutableArray array];
    self.unameSenderArray = [NSMutableArray array];
    self.coverimg = [NSString string];
    self.uname = [NSString string];
    self.unameArray = [NSMutableArray array];
    self.tingidArray = [NSMutableArray array];
    self.icon = [NSString string];
    self.musicvisitnum = [NSString string];
    self.desc = [NSString string];
    self.titleArray = [NSMutableArray array];
    
    __block typeof(self) weakSelf = self;
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *params = @{@"radioid" : _radio.radioid};
    [manager POST:kRadioDetail parameters:params success:
     
     ^(AFHTTPRequestOperation *operation, id responseObject) {
         NSData *data = operation.responseData;
         NSDictionary *dict = [NSJSONSerialization  JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         //         NSLog(@"parase json is%@",dict);
         //         NSLog(@"%@", dict[@"data"][@"list"]);
         
         // 初始化计数数组
         for (NSDictionary *item in dict[@"data"][@"list"]) {
             RadioDetail *r = [[RadioDetail new] autorelease];
             [r setValuesForKeysWithDictionary:item];
             [weakSelf.radioListArray addObject:r];
             
         }
#pragma mark - 获取传递的title
                  for (NSInteger i = 0; i < _radioListArray.count; i++) {
                      NSString *item = dict[@"data"][@"list"][i][@"playInfo"][@"title"];
                      [weakSelf.titleArray addObject:item];
                  }
//                  NSLog(@"%@", _titleArray);
         
#pragma mark - 获取传递的uname
         for (NSInteger i = 0; i < _radioListArray.count; i++) {
             NSString *item = dict[@"data"][@"list"][i][@"playInfo"][@"userinfo"][@"uname"];
             [weakSelf.unameSenderArray addObject:item];
         }
         //         NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%@", _radioListArray);
         //         NSLog(@"%ld", _radioListArray.count);
         
#pragma mark - 传递tingid
         for (NSInteger i = 0; i < _radioListArray.count; i++) {
             NSDictionary *item = dict[@"data"][@"list"][i][@"tingid"];
             [weakSelf.tingidArray addObject:item];
             
         }
         
#pragma mark - 接收背景图片地址
         weakSelf.coverimg = dict[@"data"][@"radioInfo"][@"coverimg"];
         //             NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%@", _coverimg);
#pragma mark - 获取uname
         weakSelf.uname = dict[@"data"][@"radioInfo"][@"userinfo"][@"uname"];
#pragma mark - 获取icon
         weakSelf.icon = dict[@"data"][@"radioInfo"][@"userinfo"][@"icon"];
#pragma mark - 获取musicvisitnum
         weakSelf.musicvisitnum = dict[@"data"][@"radioInfo"][@"musicvisitnum"];
#pragma mark - 获取desc
         weakSelf.desc = dict[@"data"][@"radioInfo"][@"desc"];
         
         
#pragma mark - 一定要刷新数据！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
         [self.tableView reloadData];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              
              NSLog(@"下载错误 is %@",error);
              
          }];
    
}



#pragma mark - 上拉刷新数据解析
- (void)refreshJSonData
{
    __block typeof(self) weakSelf = self;
    
    _startNumber += 10;
    NSString *startNumber = [NSString stringWithFormat:@"%ld", (long)_startNumber];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *params = @{@"radioid" : _radio.radioid, @"start" : startNumber};
    [manager POST:kRadioDetailRefresh parameters:params success:
     
     ^(AFHTTPRequestOperation *operation, id responseObject) {
         NSData *data = operation.responseData;
         NSDictionary *dict = [NSJSONSerialization  JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         
         weakSelf.countArray = [NSMutableArray array];
         for (NSDictionary *item in dict[@"data"][@"list"]) {
             RadioDetail *r = [[RadioDetail new] autorelease];
             [r setValuesForKeysWithDictionary:item];
             [weakSelf.radioListArray addObject:r];
             [weakSelf.countArray addObject:r];
         }
         
         #pragma mark - 获取传递的title
                  for (NSInteger i = 0; i < _countArray.count; i++) {
                      NSString *item = dict[@"data"][@"list"][i][@"playInfo"][@"title"];
                      [weakSelf.titleArray addObject:item];
                  }
//                  NSLog(@"%@", _titleArray);
         
#pragma mark - 获取传递的uname
         for (NSInteger i = 0; i < _countArray.count; i++) {
             NSString *item = dict[@"data"][@"list"][i][@"playInfo"][@"userinfo"][@"uname"];
             [weakSelf.unameSenderArray addObject:item];
         }
#pragma mark - 传递tingid
         for (NSInteger i = 0; i < _countArray.count; i++) {
             NSDictionary *item = dict[@"data"][@"list"][i][@"tingid"];
             [weakSelf.tingidArray addObject:item];
             
         }
         
         
//         NSLog(@"%lu", (unsigned long)_radioListArray.count);
#pragma mark - 一定要刷新数据！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
         [self.tableView reloadData];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              
              NSLog(@"下载错误 is %@",error);
              
          }];
    
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _radioListArray.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        RadioDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
        RadioDetail *rd = _radioListArray[indexPath.row];
        cell.musicVisitLabel.text = rd.musicVisit;
        cell.titlrLabel.text = _titleArray[indexPath.row];
//        NSLog(@"%@", _titleArray[indexPath.row]);
        [cell.RadioListImage sd_setImageWithURL:[NSURL URLWithString:rd.coverimg]];
    
        cell.musicVisitImage.image = [UIImage imageNamed:@"BroadcastVisitCount"];
        cell.playMusicImage.image = [UIImage imageNamed:@"AudioCellPlay"];
    
//    RadioDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
//    RadioDetail *rd = _radioListArray[indexPath.row];
//    cell.musicVisitLabel.text = rd.musicVisit;
//    cell.titlrLabel.text = rd.title;
//    [cell.RadioListImage sd_setImageWithURL:[NSURL URLWithString:rd.coverimg]];
//    
//    cell.musicVisitImage.image = [UIImage imageNamed:@"BroadcastVisitCount"];
//    cell.playMusicImage.image = [UIImage imageNamed:@"playbutton"];
    
    return cell;
}

#pragma mark - 设cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 82. / 667 * kScreenHeight;
}

#pragma mark - 设置header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 280. / 667 * kScreenHeight;
}

#pragma mark - 设置header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* customView = [[UIView new] autorelease];
    customView.backgroundColor = [UIColor whiteColor];
    
    
    // 添加背景图片
    UIImageView *backgroudImage = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(kScreenBounds), 170. / 667 * kScreenHeight)] autorelease];
    
    //设置header和cell一起滑动
    tableView.tableHeaderView = customView;
    
    [backgroudImage sd_setImageWithURL:[NSURL URLWithString:_coverimg]];
    [customView addSubview:backgroudImage];
    
    // 添加用户头像
    UIImageView *iconImage = [[[UIImageView alloc] initWithFrame:CGRectMake(20. / 375 * kScreenWidth, CGRectGetMaxY(backgroudImage.frame) + 20. / 667 * kScreenHeight, 30. / 375 * kScreenWidth, 30. / 667 * kScreenHeight)] autorelease];
    [iconImage sd_setImageWithURL:[NSURL URLWithString:_icon]];
    
#pragma mark - 调节view的圆角度
    iconImage.layer.masksToBounds = YES;
    iconImage.layer.cornerRadius = 15;
    
    [customView addSubview:iconImage];
    
    // 添加用户名
    UILabel * unameLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(iconImage.frame) + 10. / 375 * kScreenWidth, CGRectGetMaxY(backgroudImage.frame) + 20. / 667 * kScreenHeight, CGRectGetWidth(kScreenBounds) - 2 * CGRectGetMaxX(iconImage.frame), 30. / 667 * kScreenHeight)] autorelease];
    
    unameLabel.text = _uname;
    unameLabel.backgroundColor = [UIColor clearColor];
    
    // 不透明度
    unameLabel.opaque = YES;
    unameLabel.textColor = [UIColor blackColor];
    unameLabel.font = [UIFont systemFontOfSize:14];
    
    [customView addSubview:unameLabel];
    
    // 添加浏览量图片
    UIImageView *musicVisitImage = [[[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(iconImage.frame) + 230. /375 * kScreenWidth, CGRectGetMaxY(backgroudImage.frame) + 28./ 667 * kScreenHeight, 10. /375 * kScreenWidth, 15./ 667 * kScreenHeight)] autorelease];
    musicVisitImage.image = [UIImage imageNamed:@"BroadcastVisitCount"];
    
    [customView addSubview:musicVisitImage];
    
    // 添加浏览量
    UILabel *musicVisitLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(musicVisitImage.frame) + 5./375 * kScreenWidth, CGRectGetMaxY(backgroudImage.frame) + 25./375 * kScreenWidth, 80./ 667 * kScreenHeight, 20./ 667 * kScreenHeight)] autorelease];
    musicVisitLabel.text = [NSString stringWithFormat:@"%@", _musicvisitnum];
    musicVisitLabel.font = [UIFont systemFontOfSize:14];
    [customView addSubview:musicVisitLabel];
    
    // 添加作者描述
    UILabel *descLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(iconImage.frame), CGRectGetMaxY(backgroudImage.frame) + 55./ 667 * kScreenHeight, CGRectGetWidth(kScreenBounds) - 2 * CGRectGetMinX(iconImage.frame), 50./ 667 * kScreenHeight)] autorelease];
    descLabel.text = [NSString stringWithFormat:@"%@", _desc];
    descLabel.font = [UIFont systemFontOfSize:14];
    descLabel.numberOfLines = 0;
    
    [customView addSubview:descLabel];
    
    return customView;
}


#pragma mark - 推出页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        // 将tingid传递到rdlTVC
        RadioDetailListTableViewController *rdlTVC = [RadioDetailListTableViewController new] ;
        rdlTVC.tingid = _tingidArray[indexPath.row];
    
    
        // 将值传递到rdCVC
        _rdCVC = [RadioDetailContactViewController new];
        RadioDetail *rd = _radioListArray[indexPath.row];
    
    
        _rdCVC.title1 = _titleArray[indexPath.row];
        _rdCVC.radioDetail = rd;
        _rdCVC.getDataArray = _radioListArray;
        _rdCVC.getUnameArray = _unameSenderArray;
        _rdCVC.tingid0 = _tingidArray[indexPath.row];
    
    

    
    

    [[AudioPlayer ShowInstance].streamer stop];
    [self.navigationController pushViewController:_rdCVC animated:YES];
    

}


- (void)dealloc
{
    [_radio release];
    [_radioListArray release];
    [_unameSenderArray release];
    [_coverimg release];
    [_uname release];
    [_unameArray release];
    [_icon release];
    [_musicvisitnum release];
    [_desc release];
    [_tingidArray release];
    [_countArray release];
    [_tingidArray release];
    [super dealloc];
}

@end
